var http = require('http');
var paperboy = require('./lib/paperboy/paperboy');

var port = 8000;
var webroot = "../";

if(process.argv[2] !== undefined)
{
  // TODO: validate parseInt
  port = process.argv[2];
}

// TODO: Integrate getopt capabilities on the server

console.log("Running Perkins-Server in port " + port + " pointing to " + webroot + ".");
console.log("Press CTRL+C to exit.");

http.createServer(function(req, res) {
  var ip = req.connection.remoteAddress;
  paperboy
    .deliver(webroot, req, res)
    .addHeader('Expires', 300)
    .addHeader('X-PaperRoute', 'Node')
    .after(function(statCode) {
      log(statCode, req.url, ip);
    })
    .error(function(statCode, msg) {
      res.writeHead(statCode, {'Content-Type': 'text/plain'});
      res.end("Error " + statCode);
      log(statCode, req.url, ip, msg);
    })
    .otherwise(function(err) {
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end("Error 404: File not found");
      log(404, req.url, ip, err);
    });
}).listen(port);

function log(statCode, url, ip, err) {
  var logStr = statCode + ' - ' + url + ' - ' + ip;
  if (err)
    logStr += ' - ' + err;
  console.log(logStr);
}
